package org.example.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.seckill.bean.*;
import org.example.seckill.mapper.seckillOrderMapper;
import org.example.seckill.service.goodsService;
import org.example.seckill.service.orderService;
import org.example.seckill.service.seckillGoodsService;
import org.example.seckill.service.seckillOrderService;
import org.example.seckill.vo.orderStatus;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author woopsion
 * @date 2025-07-01
 */
@Service
public class seckillOrderServiceImpl extends ServiceImpl<seckillOrderMapper, seckillOrder>
implements seckillOrderService {
   
    @Autowired
    private orderService orderService;
    @Autowired
    private seckillGoodsService sgs;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     *  进行秒杀抢购，库存满足、没有重复购买的前提下！
     * @param user
     * @param gs
     * @param secGoods
     * @return
     */
    //隔离级别默认为  Repeatable  传播性质为  required 一体的
    //事物开启之后，默认就加上锁了
    @Transactional
    @Override
    public orderStatus doSeckill(User user, goods gs , seckillGoods secGoods) {
//        secGoods.setStockCount(secGoods.getStockCount()-1);
//        if(!sgs.updateById(secGoods)){return orderStatus.ORDER_ERROR_NO_RIGHT;}
        //默认 更新 操作的时候是上锁的。 update delete 操作都阻塞
        boolean update = sgs.update(new UpdateWrapper<seckillGoods>()
                .setSql("stock_count = stock_count -1")
                .eq("goods_id", gs.getId())
                .gt("stock_count", 0)
        );
        if (!update) return orderStatus.ORDER_ERROR_NO_STOCK;
        order order = new order();
        order.setUserId(user.getId());
        order.setGoodsId(gs.getId());
        order.setDeliveryAddrId(user.getId() + gs.getId());
        order.setGoodsName(gs.getGoodsName());
        order.setGoodsPrice(secGoods.getSeckillPrice());
        order.setGoodsChannel(1);
        order.setStatus(orderStatus.ORDER_UNPAID.getStatus());
        order.setCreateDate(new Date());
        //创建订单
        orderService.save(order);
        redisTemplate.opsForValue().set("order:detail:+"+user.getId()+":"+gs.getId(),order);
        seckillOrder seckillOrder = new seckillOrder();
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(gs.getId());
        this.save(seckillOrder);
        //将秒杀订单缓存起来
        redisTemplate.opsForValue().set("order:seckill:+"+user.getId()+":"+gs.getId(),seckillOrder);
        
        return orderStatus.ORDER_UNPAID;
    }
    
}
